#!/usr/bin/env python

import sys
import dotenv
from pathlib import Path
from kafka_mcp_server.server import mcp, config, TransportType, logger
from kafka_mcp_server.logging_config import setup_logging


# Initialize structured logging
logger = setup_logging()


def setup_environment():
    system_env_path = Path("/etc/kafka-mcp-server/env")
    if system_env_path.exists() and dotenv.load_dotenv(system_env_path, override=False):
        logger.info("Environment configuration loaded", source=str(system_env_path))
    elif dotenv.load_dotenv(override=False):
        logger.info("Environment configuration loaded", source="./.env")
    else:
        logger.info("Environment configuration loaded", source="environment variables", note="No .env file found")

    if not config.bootstrap_server:
        logger.error(
            "Missing required configuration",
            error="KAFKA_BOOTSTRAP_SERVER environment variable is not set",
            suggestion="Please set it to your Kafka bootstrap server",
            example="your-prometheus-server:9092"
        )
        return False

    # MCP Server configuration validation
    mcp_config = config.mcp_server_config
    if mcp_config:
        if str(mcp_config.mcp_server_transport).lower() not in TransportType.values():
            logger.error(
                "Invalid mcp transport",
                error="KAFKA_MCP_SERVER_TRANSPORT environment variable is invalid",
                suggestion="Please define one of these acceptable transports (http/sse/stdio)",
                example="http"
            )
            return False

        try:
            if mcp_config.mcp_bind_port:
                int(mcp_config.mcp_bind_port)
        except (TypeError, ValueError):
            logger.error(
                "Invalid mcp port",
                error="KAFKA_MCP_BIND_PORT environment variable is invalid",
                suggestion="Please define an integer",
                example="8080"
            )
            return False

    return True


def run_server():
    """Main entry point for the Kafka MCP Server"""
    # Setup environment
    if not setup_environment():
        logger.error("Environment setup failed, exiting")
        sys.exit(1)

    mcp_config = config.mcp_server_config
    transport = mcp_config.mcp_server_transport

    http_transports = [TransportType.HTTP.value, TransportType.SSE.value]
    print(http_transports)
    if transport in http_transports:
        mcp.run(transport=transport, host=mcp_config.mcp_bind_host, port=mcp_config.mcp_bind_port)
        logger.info("Starting Kafka MCP Server",
                    transport=transport,
                    host=mcp_config.mcp_bind_host,
                    port=mcp_config.mcp_bind_port)
    else:
        mcp.run(transport=transport)
        logger.info("Starting Kafka MCP Server", transport=transport)


if __name__ == "__main__":
    run_server()
